// pages/about/index.js
import User from "../../manager/User.js";

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 登录界面文案
    text: app.text.login,

    data: [{
      title: '芒果Daily',
      data: '与好朋友共享每日清单\n快去提醒Ta打卡吧'
    }],

    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 组件hello
    this.hello = this.selectComponent("#hello");
    console.log(this.hello)
    // 需要刷新小伙伴信息
    app.globalData.needReloadPartner = false;
  },

  login: function () {

    //获取用户授权
    wx.getUserProfile({
      desc: '正在获取', //不写不弹提示框
      success:  (resInfo) => {
        
        wx.cloud.callFunction({
          name: "login",
        }).then(res => {
          if (res.errMsg == "cloud.callFunction:ok") {
            let _openid = res.result.openid;
            let userInfo = resInfo.userInfo;
            userInfo._openid = _openid;
            
            User.login(userInfo).then(res => {
              
              app.globalData.userInfo = res.userInfo;
              wx.setStorageSync('userInfo', res.userInfo);

              app.globalData.partnerInfo = res.partnerInfo;
              wx.setStorageSync('partnerInfo', res.partnerInfo);

              // 调用hello组件的show方法，显示新用户引导页面
              // this.hello.show(userInfo.nickname);
              // 跳过引导页直接进入首页
              wx.switchTab({
                url: '/pages/indexV2/index',
              });

            }).catch((err) => {
              wx.showModal({
                title: '错误',
                content: "网络异常[0]",
                showCancel: false
              });

              console.log(err);

            });
          } else {
            wx.showModal({
              title: '错误',
              content: "网络异常[1]",
              showCancel: false
            });
          }
        }).catch((code, msg) => {
          console.log(code, msg);

          wx.showModal({
            title: '错误',
            content: "网络异常[2]",
            showCancel: false
          });
        });
      },
      fail:  (err) => {
        console.log("获取失败: ", err)
        // 拒绝授权
        if (err.errMsg == "getUserProfile:fail getUserProfile:fail auth deny") {
          wx.showModal({
            title: '请授权',
            content: '否则您无法继续使用',
            showCancel: false
          });

          this.setData({
            loading: false
          });

          return;
        }
      }
    })

    this.setData({
      loading: true
    });
  },
})